package com.xbongbong.jxc.help;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.ContractOutstockEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInstockEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.RefundInstockEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseOutstockEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.business.WorkOrderOutstockEnum;
import com.xbongbong.saas.model.IndexTypeModel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @author 吴峰
 * @date 2022/01/24 16:11
 */
@Component
public class DataBackFillHelp {

    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private IndexTypeModel indexTypeModel;

    /**
     * JXC单据拆分旧数据编辑时新增字段回显
     * @param formData 数据
     * @param businessType 业务类型
     * @author JianTao.Xiong
     * @date 2019/12/11
     */
    public void formOldData(PaasFormDataEntityExt formData, Integer businessType) throws XbbException {
        if (!StockConstant.STOCK_TYPE_LIST.contains(businessType)) {
            return;
        }
        JSONObject data = formData.getData();
        String corpid = formData.getCorpid();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        Long supplierId;
        Long customerId;
        JSONArray customer;
        List<String> field = new ArrayList<>();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = boolQuery();
        queryBuilder.filter(termQuery("corpid.keyword", corpid));
        queryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
        // 设置join_field
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, SaasMarkEnum.SAAS.getCode());
        queryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
        switch (xbbRefTypeEnum) {
            case PURCHASE_INSTOCK:
                // 【采购入库单】数据编辑时新增的供应商字段回显为上游单据【采购合同】的的供应商
                supplierId = data.getLong(PurchaseInstockEnum.SUPPLIER_ID.getAttr());
                if (Objects.isNull(supplierId)) {
                    Long purchaseContractId = data.getLong(PurchaseInstockEnum.REF_ID.getAttr());
                    queryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), purchaseContractId));

                    searchSourceBuilder.query(queryBuilder);
                    field.add(PurchaseEnum.SUPPLIER_ID.getAttr());
                    field.add(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr());
                    List<PaasFormDataEntityExt> entityExts = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_PURCHASE, field, null, null);
                    for (PaasFormDataEntityExt entityExt : entityExts) {
                        JSONObject purchaseData = entityExt.getData();
                        supplierId = purchaseData.getLong(PurchaseEnum.SUPPLIER_ID.getAttr());
                        String supplierName = purchaseData.getString(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr());
                        data.put(PurchaseInstockEnum.SUPPLIER_ID.getAttr(), supplierId);
                        data.put(PurchaseInstockEnum.SUPPLIER_ID_LINKED_TEXT.getAttr(), supplierName);
                    }
                }
                break;
            case REFUND_INSTOCK:
                customerId = data.getLong(RefundInstockEnum.CUSTOMER_ID.getAttr());
                // 【销售退货入库单】旧数据编辑时客户名称字段数据关联上游【退货退款单】的客户名称
                if (Objects.isNull(customerId)) {
                    Long refundId = data.getLong(RefundInstockEnum.REF_ID.getAttr());
                    queryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), refundId));
                    searchSourceBuilder.query(queryBuilder);
                    field.add(RefundEnum.CUSTOMER_ID.getAttr());
                    field.add(RefundEnum.CUSTOMER_ID_LINKED_TEXT.getAttr());
                    List<PaasFormDataEntityExt> entityExts = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_REFUND, field, null, null);
                    for (PaasFormDataEntityExt entityExt : entityExts) {
                        JSONObject refundData = entityExt.getData();
                        customerId = refundData.getLong(RefundEnum.CUSTOMER_ID.getAttr());
                        String customerName = refundData.getString(RefundEnum.CUSTOMER_ID_LINKED_TEXT.getAttr());
                        data.put(RefundInstockEnum.CUSTOMER_ID.getAttr(), customerId);
                        data.put(RefundInstockEnum.CUSTOMER_ID_LINKED_TEXT.getAttr(), customerName);
                    }
                }
                break;
            case RETURNED_PURCHASE_OUTSTOCK:
                String supplierName = "";
                supplierId = data.getLong(ReturnedPurchaseOutstockEnum.LINK_SUPPLIER.getAttr());
                // 【采购退货出库单】旧数据编辑时供应商字段关联【采购退货单】的供应商
                if (Objects.isNull(supplierId)) {
                    Long returnedPurchaseId = data.getLong(ReturnedPurchaseOutstockEnum.REF_ID.getAttr());
                    queryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), returnedPurchaseId));
                    searchSourceBuilder.query(queryBuilder);
                    field.add(ReturnedPurchaseEnum.SUPPLIER_ID.getAttr());
                    field.add(ReturnedPurchaseEnum.LINK_SUPPLIER_HIDE.getAttr());
                    field.add(ReturnedPurchaseEnum.LINK_SUPPLIER.getAttr());
                    field.add(ReturnedPurchaseEnum.PURCHASE_SHEET_ID.getAttr());
                    List<PaasFormDataEntityExt> entityExts = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_RETURNED_PURCHASE, field, null, null);
                    for (PaasFormDataEntityExt entityExt : entityExts) {
                        JSONObject returnedPurchaseData = entityExt.getData();
                        supplierId = returnedPurchaseData.getLong(ReturnedPurchaseEnum.SUPPLIER_ID.getAttr());
                        if (Objects.nonNull(supplierId)) {
                            supplierName = returnedPurchaseData.getString(ReturnedPurchaseEnum.LINK_SUPPLIER_HIDE.getAttr());
                        } else {
                            // 如果【采购退货单】供应商不存在，则查询再上游的【采购合同】供应商
                            Long purchaseId = returnedPurchaseData.getLong(ReturnedPurchaseEnum.PURCHASE_SHEET_ID.getAttr());
                            queryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), purchaseId));
                            searchSourceBuilder.query(queryBuilder);
                            field.clear();
                            field.add(PurchaseEnum.SUPPLIER_ID.getAttr());
                            field.add(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr());
                            List<PaasFormDataEntityExt> purchases = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_PURCHASE, field, null, null);
                            for (PaasFormDataEntityExt purchase : purchases) {
                                JSONObject purchaseData = purchase.getData();
                                supplierId = purchaseData.getLong(PurchaseEnum.SUPPLIER_ID.getAttr());
                                supplierName = purchaseData.getString(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr());
                            }
                        }
                    }
                    data.put(ReturnedPurchaseOutstockEnum.LINK_SUPPLIER.getAttr(), supplierId);
                    data.put(ReturnedPurchaseOutstockEnum.LINK_SUPPLIER_HIDE.getAttr(), supplierName);
                }
                break;
            case RETURNED_PURCHASE:
                supplierId = data.getLong(ReturnedPurchaseEnum.SUPPLIER_ID.getAttr());
                // 【采购退货单】旧数据编辑新增供应商字段回显
                if (Objects.isNull(supplierId)) {
                    Long purchaseId = data.getLong(ReturnedPurchaseEnum.PURCHASE_SHEET_ID.getAttr());
                    queryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), purchaseId));
                    searchSourceBuilder.query(queryBuilder);
                    field.add(PurchaseEnum.SUPPLIER_ID.getAttr());
                    field.add(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr());
                    List<PaasFormDataEntityExt> entityExts = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_PURCHASE, field, null, null);
                    for (PaasFormDataEntityExt entityExt : entityExts) {
                        JSONObject purchaseData = entityExt.getData();
                        supplierId = purchaseData.getLong(PurchaseEnum.SUPPLIER_ID.getAttr());
                        supplierName = purchaseData.getString(PurchaseEnum.SUPPLIER_ID_LINKED_TEXT.getAttr());
                        data.put(ReturnedPurchaseEnum.SUPPLIER_ID.getAttr(), supplierId);
                        data.put(ReturnedPurchaseEnum.LINK_SUPPLIER_HIDE.getAttr(), supplierName);
                    }
                }
                break;
            case CONTRACT_OUTSTOCK:
                customerId = data.getLong(ContractOutstockEnum.LINK_CUSTOMER.getAttr());
                // 【销售出库单】旧数据编辑时客户名称关联上游【合同订单】的数据
                if (Objects.isNull(customerId)) {
                    Long contractId = data.getLong(ContractOutstockEnum.REF_ID.getAttr());
                    queryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), contractId));
                    searchSourceBuilder.query(queryBuilder);
                    field.add(ContractEnum.LINK_CUSTOMER.getAttr());
                    field.add(ContractEnum.LINK_CUSTOMER_HIDE.getAttr());
                    List<PaasFormDataEntityExt> contracts = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_CONTRACT, field, null, null);
                    for (PaasFormDataEntityExt contract : contracts) {
                        JSONObject contractData = contract.getData();
                        customerId = contractData.getLong(ContractEnum.LINK_CUSTOMER.getAttr());
                        String customerName = contractData.getString(ContractEnum.LINK_CUSTOMER_HIDE.getAttr());
                        data.put(ContractOutstockEnum.LINK_CUSTOMER.getAttr(), customerId);
                        data.put(ContractOutstockEnum.LINK_CUSTOMER_HIDE.getAttr(), customerName);
                    }
                }
                break;
            case WORK_ORDER_OUTSTOCK:
                // 【工单出库单】编辑时新增客户、联系人、联系方式、地址字段回显
                customerId = data.getLong(WorkOrderOutstockEnum.LINK_CUSTOMER.getAttr());
                if (Objects.isNull(customerId)) {
                    // 查询工单数据
                    Long workOrderId = data.getLong(WorkOrderOutstockEnum.REF_ID.getAttr());
                    queryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(), workOrderId));
                    searchSourceBuilder.query(queryBuilder);
                    field.add(WorkOrderEnum.LINK_CUSTOMER.getAttr());
                    field.add(WorkOrderEnum.LINK_CUSTOMER_HIDE.getAttr());
                    field.add(WorkOrderEnum.LINK_CONTACT.getAttr());
                    field.add(WorkOrderEnum.LINK_CONTACT_HIDE.getAttr());
                    field.add(WorkOrderEnum.CONTACT_INFORMATION.getAttr());
                    field.add(WorkOrderEnum.ADDRESS.getAttr());
                    List<PaasFormDataEntityExt> workOrders = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_WORK_ORDER, field, null, null);
                    for (PaasFormDataEntityExt workOrder : workOrders) {
                        JSONObject workOrderData = workOrder.getData();
                        customerId = workOrderData.getLong(WorkOrderEnum.LINK_CUSTOMER.getAttr());
                        String customerName = workOrderData.getString(WorkOrderEnum.LINK_CUSTOMER_HIDE.getAttr());
                        Long contactId = workOrderData.getLong(WorkOrderEnum.LINK_CONTACT.getAttr());
                        String contactName = workOrderData.getString(WorkOrderEnum.LINK_CONTACT_HIDE.getAttr());
                        JSONArray contactInformation = workOrderData.getJSONArray(WorkOrderEnum.CONTACT_INFORMATION.getAttr());
                        JSONObject address = workOrderData.getJSONObject(WorkOrderEnum.ADDRESS.getAttr());
                        data.put(WorkOrderOutstockEnum.LINK_CUSTOMER.getAttr(), customerId);
                        data.put(WorkOrderOutstockEnum.LINK_CUSTOMER_HIDE.getAttr(), customerName);
                        data.put(WorkOrderOutstockEnum.LINK_CONTACT.getAttr(), contactId);
                        data.put(WorkOrderOutstockEnum.LINK_CONTACT_HIDE.getAttr(), contactName);
                        data.put(WorkOrderOutstockEnum.CUSTOMER_PHONE.getAttr(), contactInformation);
                        data.put(WorkOrderOutstockEnum.CUSTOMER_ADDRESS.getAttr(), address);
                    }
                }
                break;
            default:
                break;
        }
        formData.setData(data);
    }
}
